package com.gnerv.sylvanas.module.redis.autoconfigure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class DynamicRedisRoutingDataSource {

    private static final Map<String, RedisConnectionFactory> REDIS_CONNECTION_FACTORY_MAP = new ConcurrentHashMap<>();

    public RedisConnectionFactory determineDataSource() {
        String name = DynamicRedisDataSourceContextHolder.peek();
        return getDataSource(name);
    }

    public RedisConnectionFactory getDataSource(String name) {
        if (StringUtils.hasText(name) && REDIS_CONNECTION_FACTORY_MAP.containsKey(name)) {
            return REDIS_CONNECTION_FACTORY_MAP.get(name);
        } else {
            log.debug("dynamic-datasource switch to the datasource named [{}]", name);
            throw new RuntimeException("datasource named [" + name + "] is null");
        }
    }

    public Map<String, RedisConnectionFactory> setRedisConnectionFactoryMap(Map<String, RedisConnectionFactory> redisConnectionFactoryMap) {
        REDIS_CONNECTION_FACTORY_MAP.putAll(redisConnectionFactoryMap);
        return REDIS_CONNECTION_FACTORY_MAP;
    }
}
